<template>
  <div class="page-form-wrap">
    <el-form :model="editForm" ref="editInfoForm" :rules="isEdit ? editFormRule : null" label-width="100px">
      <el-form-item ref="image" label="头像:" prop="uploadFile">
        <el-upload :disabled="!isEdit"
                   class="avatar-uploader"
                   :headers="{'authorization':$store.getters.token}"
                   :action="uploadUrl"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="账户名">
        <el-input disabled v-model="editForm.acc"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="nick">
        <el-input :disabled="!isEdit" v-model="editForm.nick"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="number">
        <el-input :disabled="!isEdit" v-model="editForm.number"></el-input>
      </el-form-item>
      <el-form-item label="E-mail" prop="mail">
        <el-input :disabled="!isEdit" v-model="editForm.mail"></el-input>
      </el-form-item>
      <el-form-item label="部门">
        <el-input disabled v-model="editForm.departmentName"></el-input>
      </el-form-item>
    </el-form>

    <div class="save-wrap">
      <el-button icon="el-icon-edit-outline" type="primary" v-show="!isEdit" :disabled="isEdit"
                 @click="dialogVisible = true">修改密码
      </el-button>
      <el-button icon="el-icon-circle-close" v-show="isEdit" @click="cancelEdit">取消</el-button>
      <el-button :icon="isEdit?'el-icon-position':'el-icon-edit-outline'" type="primary"
                 @click="submitForm('editInfoForm')" :loading="loadingBtn.submitBtn">{{ isEdit ? '提交' : '修改资料' }}
      </el-button>
    </div>
    <el-dialog title="修改密码" :visible.sync="dialogVisible" @closed="closeDialog">
      <el-form ref="editPassForm" :model="passForm" label-width="100px" :rules="formRules">
        <el-form-item label="密码" prop="pwd">
          <el-input class="no-autofill-pwd" v-model="passForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input class="no-autofill-pwd" v-model="passForm.checkPass"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loadingBtn.diaSubmitBtn" type="primary" @click="submitPassForm('editPassForm')">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { userInfo } from '@/api/user'
import { update } from '@/api/system/account'
import { axiosBaseUrl } from '@/common/config/baseConfig'

export default {
  name: 'userInfo',
  data () {
    return {
      uploadUrl: axiosBaseUrl + '/api/v1/account/uploadAvatar',
      imageUrl: '',
      editForm: {
        acc: '',
        nick: '',
        number: '',
        mail: '',
        userAvatar: '',
        departmentName: ''
      },
      editFormRule: {
        nick: [
          {
            required: true,
            message: '请填写姓名',
            trigger: 'blur'
          }
        ],
        number: [
          { required: false }
        ],
        mail: [
          { required: false }
        ]
      },
      passForm: {
        pwd: '',
        checkPass: ''
      },
      formRules: {
        pwd: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            validator: this.validatePass,
            trigger: 'blur'
          }
        ],
        checkPass: [
          {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
          },
          {
            validator: this.validatePass2,
            trigger: 'blur'
          }
        ]
      },
      loadingBtn: {
        diaSubmitBtn: false,
        submitBtn: false
      },
      isEdit: true,
      dialogVisible: false
    }
  },
  methods: {
    /**
     * 选择图片
     */
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    /**
     * 上传图片回调
     */
    handleAvatarSuccess ({
      code,
      data
    }) {
      if (code === this.$constant.SUCCESS) {
        this.imageUrl = data
        this.editForm.userAvatar = data
      }
    },
    cancelEdit () {
      this.isEdit = false
      this.$refs.editInfoForm.clearValidate()
      this.init()
    },
    /**
     * 密码校验
     * @param rule
     * @param value
     * @param callback
     */
    validatePass (rule, value, callback) {
      if (this.passForm.checkPass !== '') {
        this.$refs.editPassForm.validateField('checkPass')
      }
      callback()
    },
    validatePass2 (rule, value, callback) {
      if (this.passForm.pwd && value !== this.passForm.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    },
    /**
     * 修改密码按钮
     * @param formName
     */
    submitPassForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loadingBtn.diaSubmitBtn = true
          update(this.passForm).then(({
            code,
            msg
          }) => {
            if (code === this.$constant.SUCCESS) {
              this.$message.success(msg)
              this.dialogVisible = false
            }
            this.loadingBtn.diaSubmitBtn = false
          })
        } else {
          return false
        }
      })
    },
    /**
     * 重置按钮
     * @param formName
     */
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    /**
     * 修改资料/提交按钮
     * @param formName
     */
    submitForm (formName) {
      if (this.isEdit) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loadingBtn.submitBtn = true
            update(this.editForm).then(({
              code,
              msg
            }) => {
              if (code === this.$constant.SUCCESS) {
                this.$message.success(msg)
              }
              this.loadingBtn.submitBtn = false
              this.isEdit = false
            }).catch(e => {
              this.loadingBtn.submitBtn = false
            })
          } else {
            this.isEdit = false
          }
        })
      } else {
        this.isEdit = true
        return false
      }
    },
    /**
     * 关闭分配角色弹窗
     */
    closeDialog () {
      this.passForm.pwd = ''
      this.passForm.checkPass = ''
      this.loadingBtn.diaSubmitBtn = false
      this.$nextTick(() => {
        this.$refs.editPassForm.clearValidate()
      })
    },
    init () {
      userInfo().then(({
        data,
        code
      }) => {
        if (code === this.$constant.SUCCESS) {
          this.editForm = { ...this.editForm, ...data }
          if (data.userAvatar) {
            this.imageUrl = data.userAvatar
          }
          this.passForm.id = data.id
        }
      })
    }
  },
  created () {
    this.init()
  },
  mounted () {
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px !important;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
